#include "audiotransmitter.h"
#include <QDebug>
#include <QDataStream>
#include <QThread>
#include <QCoreApplication>

AudioTransmitter::AudioTransmitter(QObject *parent)
    : QObject(parent)
    , m_socket(nullptr)
    , m_host("localhost")
    , m_port(8766)
    , m_isConnected(false)
    , m_transmissionEnabled(false)
    , m_transmissionTimer(nullptr)
    , m_transmissionInterval(33)  // 约30fps
    , m_maxBufferSize(1024 * 1024)  // 1MB缓冲区
    , m_compressionEnabled(false)
    , m_totalBytesSent(0)
    , m_packetsSent(0)
{
    setupTransmissionTimer();
    
    qDebug() << "AudioTransmitter: 初始化完成";
    qDebug() << "默认连接地址:" << m_host << ":" << m_port;
}

AudioTransmitter::~AudioTransmitter()
{
    disconnectFromServer();
    
    if (m_transmissionTimer) {
        m_transmissionTimer->stop();
        delete m_transmissionTimer;
    }
}

void AudioTransmitter::setupTransmissionTimer()
{
    m_transmissionTimer = new QTimer(this);
    m_transmissionTimer->setSingleShot(false);
    connect(m_transmissionTimer, &QTimer::timeout, this, &AudioTransmitter::onTransmissionTimer);
}

bool AudioTransmitter::connectToServer(const QString &host, quint16 port)
{
    if (m_isConnected) {
        qDebug() << "AudioTransmitter: 已经连接到服务器";
        return true;
    }
    
    // 创建新的socket连接
    if (m_socket) {
        m_socket->deleteLater();
    }
    
    m_socket = new QTcpSocket(this);
    m_host = host;
    m_port = port;
    
    // 连接信号
    connect(m_socket, &QTcpSocket::connected, this, &AudioTransmitter::onSocketConnected);
    connect(m_socket, &QTcpSocket::disconnected, this, &AudioTransmitter::onSocketDisconnected);
    connect(m_socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::errorOccurred),
            this, &AudioTransmitter::onSocketError);
    
    qDebug() << "AudioTransmitter: 正在连接到服务器" << m_host << ":" << m_port;
    
    // 尝试连接
    m_socket->connectToHost(m_host, m_port);
    
    // 等待连接完成（最多等待5秒）
    if (m_socket->waitForConnected(5000)) {
        qDebug() << "AudioTransmitter: 连接成功";
        return true;
    } else {
        qWarning() << "AudioTransmitter: 连接超时";
        emit error("连接服务器超时");
        return false;
    }
}

void AudioTransmitter::disconnectFromServer()
{
    if (m_transmissionTimer) {
        m_transmissionTimer->stop();
    }
    
    if (m_socket) {
        if (m_socket->state() != QAbstractSocket::UnconnectedState) {
            m_socket->disconnectFromHost();
            if (m_socket->state() != QAbstractSocket::UnconnectedState) {
                m_socket->waitForDisconnected(3000);
            }
        }
        m_socket->deleteLater();
        m_socket = nullptr;
    }
    
    m_isConnected = false;
    
    // 清空音频队列
    QMutexLocker locker(&m_queueMutex);
    m_audioQueue.clear();
    
    emit connectionStatusChanged(false);
    qDebug() << "AudioTransmitter: 已断开连接";
}

bool AudioTransmitter::isConnected() const
{
    return m_isConnected && m_socket && m_socket->state() == QAbstractSocket::ConnectedState;
}

void AudioTransmitter::sendAudioData(const QByteArray &audioData)
{
    qDebug() << "AudioTransmitter: 发送音频数据";
    if (!m_transmissionEnabled || !m_isConnected) {
        qDebug() << "AudioTransmitter: 音频传输未启用或未连接" << m_transmissionEnabled << m_isConnected;
        return;
    }
    
    if (audioData.isEmpty()) {
        qDebug() << "AudioTransmitter: 音频数据为空";
        return;
    }
    
    // 添加到音频队列
    QMutexLocker locker(&m_queueMutex);
    
    // 检查缓冲区大小
    if (m_audioQueue.size() >= m_maxBufferSize / 4096) {  // 假设每个音频块4KB
        qWarning() << "AudioTransmitter: 音频缓冲区已满，丢弃最旧的数据";
        m_audioQueue.dequeue();
    }
    
    m_audioQueue.enqueue(audioData);
    
    // 如果传输定时器未启动，启动它
    if (!m_transmissionTimer->isActive()) {
        m_transmissionTimer->start(m_transmissionInterval);
    }
    
    qDebug() << "AudioTransmitter: 音频数据已加入队列，大小:" << audioData.size() << "字节";
}

void AudioTransmitter::setTransmissionEnabled(bool enabled)
{
    if (m_transmissionEnabled == enabled) {
        return;
    }
    
    m_transmissionEnabled = enabled;
    
    if (enabled) {
        qDebug() << "AudioTransmitter: 音频传输已启用";
        if (m_transmissionTimer && !m_transmissionTimer->isActive()) {
            m_transmissionTimer->start(m_transmissionInterval);
        }
    } else {
        qDebug() << "AudioTransmitter: 音频传输已禁用";
        if (m_transmissionTimer) {
            m_transmissionTimer->stop();
        }
    }
    
    emit transmissionStatusChanged(enabled);
}

bool AudioTransmitter::isTransmissionEnabled() const
{
    return m_transmissionEnabled;
}

void AudioTransmitter::setBufferSize(int size)
{
    m_maxBufferSize = qMax(1024 * 1024, size);  // 最小1MB
    qDebug() << "AudioTransmitter: 缓冲区大小设置为" << m_maxBufferSize << "字节";
}

void AudioTransmitter::setTransmissionInterval(int intervalMs)
{
    m_transmissionInterval = qMax(10, intervalMs);  // 最小10ms
    if (m_transmissionTimer && m_transmissionTimer->isActive()) {
        m_transmissionTimer->start(m_transmissionInterval);
    }
    qDebug() << "AudioTransmitter: 传输间隔设置为" << m_transmissionInterval << "ms";
}

void AudioTransmitter::setCompressionEnabled(bool enabled)
{
    m_compressionEnabled = enabled;
    qDebug() << "AudioTransmitter: 音频压缩" << (enabled ? "已启用" : "已禁用");
}

void AudioTransmitter::onSocketConnected()
{
    m_isConnected = true;
    emit connectionStatusChanged(true);
    emit connectionEstablished();
    
    qDebug() << "AudioTransmitter: 已连接到服务器";
    
    // 如果传输已启用，启动传输定时器
    if (m_transmissionEnabled) {
        m_transmissionTimer->start(m_transmissionInterval);
    }
}

void AudioTransmitter::onSocketDisconnected()
{
    m_isConnected = false;
    emit connectionStatusChanged(false);
    emit connectionLost();
    
    qDebug() << "AudioTransmitter: 与服务器断开连接";
    
    // 停止传输定时器
    if (m_transmissionTimer) {
        m_transmissionTimer->stop();
    }
}

void AudioTransmitter::onSocketError(QAbstractSocket::SocketError error)
{
    QString errorString = m_socket ? m_socket->errorString() : "未知错误";
    qWarning() << "AudioTransmitter: Socket错误:" << error << "-" << errorString;
    
    emit this->error(QString("网络错误: %1").arg(errorString));
    
    // 尝试重新连接
    if (m_isConnected) {
        qDebug() << "AudioTransmitter: 尝试重新连接...";
        QTimer::singleShot(5000, this, [this]() {
            if (!m_isConnected) {
                connectToServer(m_host, m_port);
            }
        });
    }
}

void AudioTransmitter::onTransmissionTimer()
{
    if (!m_transmissionEnabled || !m_isConnected) {
        qDebug() << "AudioTransmitter: 传输定时器触发，但传输未启用或未连接";
        return;
    }
    
    processAudioQueue();
}

void AudioTransmitter::processAudioQueue()
{
    QMutexLocker locker(&m_queueMutex);
    
    if (m_audioQueue.isEmpty()) {
        return;
    }
    
    // 处理队列中的所有音频数据
    while (!m_audioQueue.isEmpty()) {
        QByteArray audioData = m_audioQueue.dequeue();
        
        if (m_compressionEnabled) {
            audioData = compressAudioData(audioData);
        }
        
        sendDataPacket(audioData);
    }
}

void AudioTransmitter::sendDataPacket(const QByteArray &data)
{
    if (!m_socket || m_socket->state() != QAbstractSocket::ConnectedState) {
        return;
    }
    
    // 发送数据包
    qint64 bytesWritten = m_socket->write(data);
    
    if (bytesWritten > 0) {
        m_totalBytesSent += bytesWritten;
        m_packetsSent++;
        
        emit dataSent(bytesWritten);
        
        // 等待数据写入完成
        if (!m_socket->waitForBytesWritten(1000)) {
            qWarning() << "AudioTransmitter: 数据写入超时";
        }
        
        qDebug() << "AudioTransmitter: 发送音频数据包，大小:" << bytesWritten << "字节";
    } else {
        qWarning() << "AudioTransmitter: 发送数据失败";
        emit error("发送数据失败");
    }
}

QByteArray AudioTransmitter::compressAudioData(const QByteArray &audioData)
{
    // 简单的音频数据压缩（这里可以实现更复杂的压缩算法）
    // 目前只是返回原始数据，可以根据需要添加实际的压缩逻辑
    
    // 示例：简单的数据压缩（去除静音或低音量部分）
    QByteArray compressedData;
    const qint16 *samples = reinterpret_cast<const qint16*>(audioData.constData());
    int sampleCount = audioData.size() / sizeof(qint16);
    
    // 计算音量阈值
    qint16 threshold = 100;  // 可调整的阈值
    
    for (int i = 0; i < sampleCount; ++i) {
        if (qAbs(samples[i]) > threshold) {
            compressedData.append(reinterpret_cast<const char*>(&samples[i]), sizeof(qint16));
        }
    }
    
    // 如果压缩后数据为空，返回原始数据
    if (compressedData.isEmpty()) {
        return audioData;
    }
    
    qDebug() << "AudioTransmitter: 音频数据压缩:" << audioData.size() << "->" << compressedData.size() << "字节";
    return compressedData;
}
